#include "includes.h"

unsigned char reset_pulse(void){
	unsigned char i;
	THERM_LOW();
	THERM_OUTPUT_MODE();
	_delay_us(500);
	THERM_INPUT_MODE();
	
	_delay_us(60); //60
	i=(THERM_PIN & (1<<THERM_DQ));
	_delay_us(420);
	return i;
}

void write_bit(unsigned char bit){
	
	THERM_LOW();
	THERM_OUTPUT_MODE();
	_delay_us(1);
	if(bit)	THERM_INPUT_MODE();//write 1
	_delay_us(60);
	THERM_INPUT_MODE();//write 0
		
}

void write_byte(unsigned char byte){
	
	unsigned char i=8;
	while(i--)
	{
		//Write actual bit and shift one position right to make the next bit ready
		write_bit(byte&1);
		byte>>=1;
	}
	
	
}

unsigned char read_bit(void)
{
	unsigned char bit=0;
	//Pull line low for 1uS
	THERM_LOW();
	THERM_OUTPUT_MODE();
	_delay_us(1);//1
	//Release line and wait for 14uS
	THERM_INPUT_MODE();
	_delay_us(10);//14
	//Read line value
	if(THERM_PIN&(1<<THERM_DQ)) bit=1;
	//Wait for 45uS to end and return read value
	_delay_us(40);//45
	return bit;
}

unsigned char read_byte(void)
{
	unsigned char i=8, n=0;
	while(i--)
	{
		//Shift one position right and store read value
		n>>=1;
		n|=(read_bit()<<7);
	}
	return n;
}

void read_temp(void){

	reset_pulse();
	write_byte(THERM_CMD_SKIPROM);
	write_byte(THERM_CMD_CONVERTTEMP);
	//Wait until conversion is complete
	while(read_bit());
	//Reset, skip ROM and send command to read Scratchpad
	reset_pulse();
	write_byte(THERM_CMD_SKIPROM);
	write_byte(THERM_CMD_RSCRATCHPAD);
	//Read Scratchpad (only 2 first bytes)
	temperature[0]=read_byte();
	temperature[1]=read_byte();
	reset_pulse();
}

void read_temperature(void)
{
		unsigned char temp,temp2,zeci,unitati;
		read_temp();
		temp=temperature[0]/2;
		temp2=temperature[0];
		
		//PORTC=temperature[1];
		if(temperature[1]){
				

				//USART_Transmit_s(" -");
				lcd_puts(" -");
				_delay_ms(1);
				//temp2/=2;
				
				
				zeci=(~temp2)/2;///10;
				zeci=zeci&0b0111111;
				temp=zeci;
				_delay_ms(1);
				//USART_Transmit(zeci/10+'0');
				lcd_putc(zeci/10+'0');
				_delay_ms(1);
			
				unitati=(zeci)%10;
				//USART_Transmit(unitati+'0');
				lcd_putc(unitati+'0');
				_delay_ms(1);
		
				if(temperature[0]&0x01)
										{
											lcd_puts(".5 ");
											_delay_ms(1);
										}
				
				
		}else{		
			
			zeci=temp/10;
			lcd_putc(zeci+'0');
			_delay_ms(1);
			
			unitati=temp%10;
			lcd_putc(unitati+'0');
			_delay_ms(1);
		
			if(temperature[0]&0x01)
									{
										lcd_puts(".5 ");
										_delay_ms(1);
									}
		}
		
	_delay_ms(100);
	
}
	